<?php

namespace app\controller\crm;

use app\BaseController;
use app\common\DataPermissionHelper;
use think\facade\Db;
use think\facade\Request;

/**
 * 订单管理
 */
class NewOrder extends BaseController
{
    /**
     * 获取订单列表
     */
    public function list()
    {
        $params = Request::param();
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 20;
        $customerName = $params['customer_name'] ?? '';
        $orderSubType = $params['order_sub_type'] ?? '';
        $approvalStatus = $params['approval_status'] ?? '';
        $deliveryStatus = $params['delivery_status'] ?? '';

        $query = Db::name('crm_order')
            ->alias('o')
            ->field('o.*, c.name as customer_name, c.customer_type, ct.name as contact_name, u.name as signer_name, ot.type_name as order_type_name')
            ->leftJoin('crm_customer c', 'o.customer_id = c.id')
            ->leftJoin('crm_contact ct', 'o.contact_id = ct.id')
            ->leftJoin('admin u', 'o.signer_id = u.id')
            ->leftJoin('crm_order_type ot', 'o.type_id = ot.id')
            ->where('o.delete_time', 0);

        if ($customerName) {
            $query->where('o.customer_name', 'like', '%' . $customerName . '%');
        }

        if ($orderSubType) {
            $query->where('o.order_sub_type', $orderSubType);
        }

        if ($approvalStatus !== '') {
            $query->where('o.approval_status', $approvalStatus);
        }

        if ($deliveryStatus !== '') {
            $query->where('o.delivery_status', $deliveryStatus);
        }

        // 数据权限控制
        $userId = $this->getUserId();
        if ($userId > 0) {
            $userInfo = Db::name('admin')
                ->field('id, group_id, did')
                ->where('id', $userId)
                ->find();

            if ($userInfo) {
                // 超级管理员和部门经理可以查看所有数据
                if ($userInfo['group_id'] == 1 || $userInfo['group_id'] == 2) {
                    // 部门经理只能查看本部门数据
                    if ($userInfo['group_id'] == 2) {
                        $query->where('o.department_id', $userInfo['did']);
                    }
                } else {
                    // 销售人员只能查看自己的数据
                    $query->where('o.signer_id', $userId);
                }
            }
        }

        $total = $query->count();
        $list = $query->order('o.create_time', 'desc')
            ->page($page, $limit)
            ->select();

        return $this->paginate($list ? $list->toArray() : [], $total, (int)$page, (int)$limit);
    }

    /**
     * 获取订单详情
     */
    public function detail()
    {
        $id = Request::param('id');
        if (!$id) {
            return $this->error('参数错误');
        }

        $order = Db::name('crm_order')
            ->alias('o')
            ->field('o.*, c.name as customer_name, c.customer_type, ct.name as contact_name, ct.phone as contact_phone')
            ->leftJoin('crm_customer c', 'o.customer_id = c.id')
            ->leftJoin('crm_contact ct', 'o.contact_id = ct.id')
            ->where('o.id', $id)
            ->where('o.delete_time', 0)
            ->find();

        if (!$order) {
            return $this->error('订单不存在');
        }

        // 检查数据权限
        if (!$this->checkDataPermission($order)) {
            return $this->error('没有权限访问此数据', 403);
        }

        // 获取关联的财务记录
        $financeRecords = Db::name('crm_finance_record')
            ->where('order_id', $id)
            ->order('create_time', 'desc')
            ->select();

        // 获取关联的合同归档信息
        $contractArchive = Db::name('crm_contract_archive')
            ->where('order_id', $id)
            ->find();

        // 获取关联的工单
        $workOrder = Db::name('work_order')
            ->where('order_id', $id)
            ->find();

        $order['finance_records'] = $financeRecords ? $financeRecords->toArray() : [];
        $order['contract_archive'] = $contractArchive;
        $order['work_order'] = $workOrder;

        return $this->success($order);
    }

    /**
     * 创建订单
     */
    public function create()
    {
        $params = Request::param();
        $userId = $this->getUserId();

        if (!$userId) {
            return $this->error('未登录或登录已过期', 401);
        }

        // 获取用户部门信息
        $userInfo = Db::name('admin')
            ->field('did, name')
            ->where('id', $userId)
            ->find();

        // 获取客户信息
        $customer = Db::name('crm_customer')->where('id', $params['customer_id'])->find();
        if (!$customer) {
            return $this->error('客户不存在');
        }

        // 获取联系人信息
        $contact = null;
        if ($params['contact_id']) {
            $contact = Db::name('crm_contact')->where('id', $params['contact_id'])->find();
        }

        // 生成订单编号
        $orderNo = $this->generateOrderNo();

        // 检查是否是会员客户的免费法务专项订单
        $isFreeOrder = false;
        if ($params['order_sub_type'] == 3) {  // 法务专项
            $checkResult = $this->checkMemberFreeOrder($params['customer_id']);
            if ($checkResult['can_use']) {
                $isFreeOrder = true;
                $params['total_amount'] = 0;  // 免费订单金额为0
            }
        }

        $data = [
            'order_no' => $orderNo,
            'customer_id' => $params['customer_id'],
            'customer_name' => $customer['name'],
            'customer_type' => $customer['customer_type'],
            'id_number' => $customer['id_number'] ?? '',
            'contact_id' => $params['contact_id'] ?? null,
            'contact_name' => $contact ? $contact['name'] : '',
            'contact_phone' => $contact ? $contact['phone'] : '',
            'opportunity_id' => $params['opportunity_id'] ?? null,
            'order_sub_type' => $params['order_sub_type'],
            'type_id' => $params['type_id'],
            'contract_no' => $params['contract_no'] ?? '',
            'contract_amount' => $params['contract_amount'] ?? 0,
            'post_amount' => $params['post_amount'] ?? 0,
            'total_amount' => $params['total_amount'] ?? 0,
            'paid_amount' => 0,
            'signer_id' => $userId,
            'signer_name' => $userInfo['name'],
            'contract_start_date' => isset($params['contract_start_date']) ? strtotime($params['contract_start_date']) : null,
            'contract_end_date' => isset($params['contract_end_date']) ? strtotime($params['contract_end_date']) : null,
            'contract_sign_date' => isset($params['contract_sign_date']) ? strtotime($params['contract_sign_date']) : null,
            'approval_status' => 0,  // 待审核
            'delivery_status' => 0,  // 待交付
            'department_id' => $userInfo['did'],
            'create_time' => time(),
            'update_time' => time()
        ];

        $id = Db::name('crm_order')->insertGetId($data);

        if ($id) {
            // 如果有关联的机会线索，标记为已转化
            if ($params['opportunity_id']) {
                Db::name('crm_opportunity')->where('id', $params['opportunity_id'])->update([
                    'status' => 2,  // 已转化
                    'order_id' => $id,
                    'update_time' => time()
                ]);
            }

            return $this->success(['id' => $id, 'order_no' => $orderNo], '订单创建成功');
        }

        return $this->error('订单创建失败');
    }

    /**
     * 取消订单
     */
    public function cancel()
    {
        $id = Request::param('id');
        if (!$id) {
            return $this->error('参数错误');
        }

        // 检查订单是否存在
        $order = Db::name('crm_order')->where('id', $id)->find();
        if (!$order) {
            return $this->error('订单不存在');
        }

        // 检查数据权限
        if (!$this->checkDataPermission($order)) {
            return $this->error('没有权限操作此数据', 403);
        }

        // 检查订单状态
        if ($order['approval_status'] == 2) {
            return $this->error('已审核通过的订单不能取消');
        }

        $result = Db::name('crm_order')->where('id', $id)->update([
            'approval_status' => 4,  // 已取消
            'update_time' => time()
        ]);

        if ($result !== false) {
            return $this->success([], '订单取消成功');
        }

        return $this->error('订单取消失败');
    }

    /**
     * 提交审核
     */
    public function submit()
    {
        $id = Request::param('id');
        if (!$id) {
            return $this->error('参数错误');
        }

        // 检查订单是否存在
        $order = Db::name('crm_order')->where('id', $id)->find();
        if (!$order) {
            return $this->error('订单不存在');
        }

        // 检查数据权限
        if (!$this->checkDataPermission($order)) {
            return $this->error('没有权限操作此数据', 403);
        }

        // 检查订单状态
        if ($order['approval_status'] != 0) {
            return $this->error('订单已提交或已审核');
        }

        $result = Db::name('crm_order')->where('id', $id)->update([
            'approval_status' => 1,  // 审核中
            'update_time' => time()
        ]);

        if ($result !== false) {
            return $this->success([], '提交审核成功');
        }

        return $this->error('提交审核失败');
    }

    /**
     * 检查数据权限
     */
    private function checkDataPermission($order)
    {
        $userId = $this->getUserId();
        if (!$userId) {
            return false;
        }

        $userInfo = Db::name('admin')
            ->field('id, group_id, did')
            ->where('id', $userId)
            ->find();

        if (!$userInfo) {
            return false;
        }

        // 超级管理员
        if ($userInfo['group_id'] == 1) {
            return true;
        }

        // 部门经理
        if ($userInfo['group_id'] == 2) {
            return $userInfo['did'] == $order['department_id'];
        }

        // 销售人员只能操作自己的数据
        return $order['signer_id'] == $userId;
    }

    /**
     * 生成订单编号
     */
    private function generateOrderNo()
    {
        $prefix = 'ORD';
        $date = date('Ymd');
        $lastOrder = Db::name('crm_order')
            ->where('order_no', 'like', $prefix . $date . '%')
            ->order('id', 'desc')
            ->find();

        if ($lastOrder) {
            $lastNo = substr($lastOrder['order_no'], -6);
            $seq = str_pad($lastNo + 1, 6, '0', STR_PAD_LEFT);
        } else {
            $seq = '000001';
        }

        return $prefix . $date . $seq;
    }

    /**
     * 检查会员免费订单
     */
    private function checkMemberFreeOrder($customerId)
    {
        // 检查客户是否为会员
        $customer = Db::name('crm_customer')
            ->where('id', $customerId)
            ->find();

        if (!$customer || $customer['customer_attribute'] != 3) {
            return ['can_use' => false, 'message' => '非会员客户'];
        }

        // 检查会员是否在服务期内
        $membership = Db::name('customer_membership')
            ->where('customer_id', $customerId)
            ->where('status', 1)
            ->where('service_end_date', '>', time())
            ->find();

        if (!$membership) {
            return ['can_use' => false, 'message' => '会员服务已过期'];
        }

        return ['can_use' => true, 'message' => '可享受免费法务专项服务'];
    }
}
